package com.hoperun.udpbroadcast.broadcast;

import com.hoperun.udpbroadcast.Log;
import ohos.eventhandler.EventHandler;
import ohos.eventhandler.EventRunner;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.nio.charset.StandardCharsets;

public class UdpBroadcastClient {
    EventHandler eventHandler;
    private String broadcastIp = "192.168.40.255";       //广播范围
    private int broadcastPort = 8888;     //端口
    DatagramSocket socket;

    public UdpBroadcastClient() {
        eventHandler = new EventHandler(EventRunner.create());
    }

    public void setSocket(DatagramSocket socket) {
        this.socket = socket;
    }

    public void setAddress(String ip, int port) {
        broadcastIp = ip;
        broadcastPort = port;
    }

    public void send(String str) {
        eventHandler.postTask(() -> sendBroadcast(str.getBytes(StandardCharsets.UTF_8)));
    }

    private void sendBroadcast(byte[] sendBuf) {
        Log.println("sendBroadcast %s", new String(sendBuf));
        if (socket != null) {
            try {
                send(sendBuf, socket);
            } catch (IOException e) {
                e.printStackTrace();
                Log.w("send Broadcast", e);
            }
        } else {
            try (DatagramSocket socket = new DatagramSocket(broadcastPort)) {
                send(sendBuf, socket);

            } catch (IOException e) {
                e.printStackTrace();
                Log.w("send Broadcast", e);
            }
        }

    }

    private void send(byte[] sendBuf, DatagramSocket socket) throws IOException {
        InetAddress address = InetAddress.getByName(broadcastIp);
        DatagramPacket sendPacket = new DatagramPacket(sendBuf, sendBuf.length, address, broadcastPort);
        socket.send(sendPacket);
        socket.setBroadcast(true);
    }

}
